/**
 * 管理系统-文章-接口路由模块
 */
const express = require('express')
const router = express.Router()

/**
 * 引入其他模块
 */
const db = require('../../utils/db')
const upload = require('../../middlewares/upload')

// 添加文章
router.post('/api/post/add', upload.single('article_file'), (req, res, next) => {
  const { body } = req
  console.log('req--', req)
  const sql = `
    insert into ali_article
    (
      article_title,
      article_body,
      article_slug,
      article_file,
      article_cateid,
      article_addtime,
      article_status,
      article_adminid
    )
    values
    (?,?,?,?,?,?,?,?)`
  db.query(sql, [
    body.article_title,
    body.article_body,
    body.article_slug,
    `/public/uploads/${req.file.filename}`,
    body.article_cateid,
    body.article_addtime,
    body.article_status,
    req.session.user.admin_id
  ], (err, result) => {
    if (err) return next(err)
    res.status(200).json({
      success: true
    })
  })
})

// 编辑文章
router.post('/api/post/edit', (req, res, next) => {
  const {id} = req.query
  const {body} = req
  console.log("req.query---", req.query)
  console.log("req.body---", req.body)
  const sql = `
    update
      ali_article
    set
      article_title = ?,
      article_body = ?,
      article_slug = ?,
      article_file = ?,
      article_cateid = ?,
      article_addtime = ?,
      article_status = ?
    where
      article_id = ?
  `
  db.query(sql, [
    body.article_title,
    body.article_body,
    body.article_slug,
    body.new_file || body.original_file,
    body.article_cateid,
    body.article_addtime,
    body.article_status,
    id
  ], (err, result) => {
    if (err) return next(err)
    res.status(200).json({
      success: true
    })
  })
})

// 删除单篇文章
router.post('/api/post/singleDelete', (req, res, next) => {
  const sql = 'delete from ali_article where article_id = ?'
  db.query(sql, req.body.id, (err, result) => {
    if (err) return next(err)
    res.status(200).json({
      success: true
    })
  })
})

// 批量删除文章
router.post('/api/post/batchDelete', (req, res, next) => {
  const sql = `delete from ali_article where article_id in (${req.body.ids})`
  console.log(req.body)
  db.query(sql, (err, result) => {
    if (err) return next(err)
    res.status(200).json({
      success: true
    })
  })
})

module.exports = router